import { createStore } from 'vuex'
import axios from 'axios'
import authApi from '@/api/auth'
export default createStore({
    state: {
        user: {
            username: '',
            token: ''
        }
    },
    mutations: {
        SET_USER(state, payload) {
            state.user.username = payload.username
            state.user.token = payload.token
            // 保存到localStorage
            localStorage.setItem('username', payload.username)
            localStorage.setItem('token', payload.token)

            // 设置axios默认授权头
            if (payload.token) {
                axios.defaults.headers.common['Authorization'] = `Bearer ${payload.token}`
            }
        },
        CLEAR_USER(state) {
            state.user.username = ''
            state.user.token = ''
            localStorage.removeItem('username')
            localStorage.removeItem('token')
            delete axios.defaults.headers.common['Authorization']
        }
    },
    actions: {
        // 登录action
        async login({ commit }, { username, password }) {
            console.log('store login')
            const response = await authApi.login(username, password)
            commit('SET_USER', {
                username,
                token: response.data.token
            })
            return response.data
        },
        // 退出登录action
        async logout({ commit }) {
            try {
                await authApi.logout()
            } finally {
                commit('CLEAR_USER')
            }
        },

        // 初始化用户状态
        initializeUser({ commit }) {
            const username = localStorage.getItem('username')
            const token = localStorage.getItem('token')
            if (token && username) {
                commit('SET_USER', {
                    username,
                    token
                })
            }
        }
    },



    getters: {
        username: (state) => state.user.username
    }
})